import request from '@/config/request'
import { getAnswerScoreable, jywConvertToXkw } from '@/utils/question'
import { getAllSubjectApi, getSelfModuleSubjectApi, questionSplitApi } from '@/api/common'

// 获取题型
export const getQuestionType = (data) => {
  return request.get('/app-api/question/App/type/get', data)
}

// 获得已有打卡任务的科目列表
export const getSubjectApi = () => {
  return new Promise((resolve) => {
    Promise.all([
      getAllSubjectApi({
        formatter: (subjects) => {
          return subjects.map((item) => {
            return item.value
          })
        }
      }),
      getSelfModuleSubjectApi()
    ]).then((res) => {
      const [subjectIdListData, moduleSubjectListData] = res
      const { data: subjectIdList } = subjectIdListData
      const { data: moduleSubjectList } = moduleSubjectListData

      // 获取已经开通的科目
      if (Array.isArray(moduleSubjectList) && moduleSubjectList.length > 0) {
        const selfSubjectList = moduleSubjectList.filter((i) => i.moduleId === '8')
        if (Array.isArray(subjectIdList) && selfSubjectList.length > 0) {
          const copySubjectIdList = JSON.parse(JSON.stringify(subjectIdList))
          const selfSubjectIds = selfSubjectList.map((i) => i.subject)
          subjectIdList.splice(0, subjectIdList.length)
          subjectIdList.push(...copySubjectIdList.filter((i) => selfSubjectIds.includes(i)))
        } else {
          subjectIdList.splice(0, subjectIdList.length)
        }
      } else {
        subjectIdList.splice(0, subjectIdList.length)
      }

      resolve(subjectIdListData)
    })
  })
}

// 获取每日打卡任务列表
export const getAppStudyClockinListApi = (data) => {
  return request.get('/app-api/exam/app/study-clockin/getAppStudyClockinList', data)
}

// 去打卡（旧的）
export const goStudyClockinApi = (data) => {
  const { studyClockinId = '', studyClockinType = '' } = data
  const params = `studyClockinId=${studyClockinId}&studyClockinType=${studyClockinType}`

  return request.post(`/app-api/exam/app/study-clockin/goStudyClockin?${params}`)
}

// 去打卡-举一反三
export const goStudyClockinRecommendApi = (data) => {
  return new Promise(async (resovle) => {
    const res = await request.post(`/app-api/question/recommend-question/goClockin`, data)

    try {
      if (res.data) {
        const q = res.data
        // 如果不是学科网题目，将题目改为学科网的题目结构
        // 菁优网
        if (q.sourceType && q.sourceType === '3') {
          jywConvertToXkw(q)

          // 题目解析
          const { data: questionSplitRes = [] } = await questionSplitApi([
            {
              questionId: q.questionId,
              stem: q.stem,
              answer: q.answer,
              explanation: q.explanation
            }
          ])

          q.question = {}
          q.question.stem = JSON.parse(
            questionSplitRes[0].stem.replace(
              /<fieldset style=\\\"margin-top:0.1rem;font-size:0.26rem\\\">\\n /,
              '<fieldset style=\\"margin-top:0.1rem;font-size:0.26rem\\">'
            )
          )
          q.question.answer = JSON.parse(questionSplitRes[0].answer)
          q.question.explanation = JSON.parse(questionSplitRes[0].explanation)
        }

        const {
          data: { typeId, typeName }
        } = res

        if (!typeName) {
          const { data } = await getQuestionType({ id: typeId })
          res.data.typeName = data && data.name ? data.name : '未知题型'
        }

        res.data.answerScoreable = getAnswerScoreable({
          stem: res.data.question.stem,
          answer: res.data.question.answer
        })
      }
    } catch (error) {
      console.error(error)
    }

    resovle(res)
  })
}

// 去打卡-习题中心
export const goStudyClockinPracticeApi = (data) => {
  return new Promise(async (resovle) => {
    const res = await request.post(`/app-api/exam/kpointPractice/goClockin`, data)

    try {
      if (res.data) {
        Promise.all(
          res.data.map(async (question) => {
            const { sourceType, questionId, typeId, typename: typeName } = question

            // 如果不是学科网题目，将题目改为学科网的题目结构
            const q = question
            // 菁优网
            if (sourceType && sourceType === '3') {
              // 获取题目详情
              const { data: questionSource } = await getListCompleteByIdsApi({
                ids: questionId
              })
              q.typeName = typeName
              q.infoFlag = 1
              if (questionSource) {
                q.kpointIds = questionSource[0].kpointIds
                q.answer = questionSource[0].answer
                q.displayAnswer = questionSource[0].displayAnswer
                q.explanation = questionSource[0].explanation
                q.method = questionSource[0].method
                q.discuss = questionSource[0].discuss
              }
              jywConvertToXkw(q)

              // 题目解析
              const { data: questionSplitRes = [] } = await questionSplitApi([
                {
                  questionId: q.questionId,
                  stem: q.stem,
                  answer: q.answer,
                  explanation: q.explanation
                }
              ])

              q.question = {}
              q.question.stem = JSON.parse(
                questionSplitRes[0].stem.replace(
                  /<fieldset style=\\\"margin-top:0.1rem;font-size:0.26rem\\\">\\n /,
                  '<fieldset style=\\"margin-top:0.1rem;font-size:0.26rem\\">'
                )
              )
              q.question.answer = JSON.parse(questionSplitRes[0].answer)
              q.question.explanation = JSON.parse(questionSplitRes[0].explanation)
            }

            if (!typeName) {
              const { data } = await getQuestionType({ id: typeId })
              question.typeName = data && data.name ? data.name : '未知题型'
            }

            question.answerScoreable = getAnswerScoreable({
              stem: question.question.stem,
              answer: question.question.answer
            })

            return question
          })
        ).then((questions) => {
          // 筛选有知识点的题目
          const data = questions
            .map((question) => {
              if (question.kpointIds != '[]') {
                return question
              } else {
                return null
              }
            })
            .filter((item) => item)

          if (Array.isArray(data) && data.length > 0) {
            res.data = data
          } else {
            res.code = 499
            res.data = null
            res.msg = '没有符合要求的题目'
          }
          resovle(res)
        })
      } else {
        resovle(res)
      }
    } catch (error) {
      resovle(res)
      console.error(error)
    }
  })
}

// 去打卡-习题中心-跳过题目
export const skipForClockinApi = (data) => {
  const { subject, kpointIds, difficultyLevel, typeId } = data
  const params = `subject=${subject}&kpointIds=${kpointIds}&difficultyLevel=${difficultyLevel}&typeId=${typeId}`
  return new Promise(async (resovle) => {
    const res = await request.get(`/app-api/exam/kpointPractice/skipForClockin?${params}`)

    try {
      // 如果不是学科网题目，将题目改为学科网的题目结构
      const q = res.data
      // 菁优网
      if (q.sourceType && q.sourceType === '3') {
        // 获取题目详情
        const { data: questionSource } = await getListCompleteByIdsApi({
          ids: q.questionId
        })
        q.typeName = q.typename
        q.infoFlag = 1
        if (questionSource) {
          q.answer = questionSource[0].answer
          q.displayAnswer = questionSource[0].displayAnswer
          q.explanation = questionSource[0].explanation
          q.method = questionSource[0].method
          q.discuss = questionSource[0].discuss
        }
        jywConvertToXkw(q)

        // 题目解析
        const { data: questionSplitRes = [] } = await questionSplitApi([
          {
            questionId: q.questionId,
            stem: q.stem,
            answer: q.answer,
            explanation: q.explanation
          }
        ])

        q.question = {}
        q.question.stem = JSON.parse(
          questionSplitRes[0].stem.replace(
            /<fieldset style=\\\"margin-top:0.1rem;font-size:0.26rem\\\">\\n /,
            '<fieldset style=\\"margin-top:0.1rem;font-size:0.26rem\\">'
          )
        )
        q.question.answer = JSON.parse(questionSplitRes[0].answer)
        q.question.explanation = JSON.parse(questionSplitRes[0].explanation)
        q.courseId = subject
      }

      if (res.data) {
        const {
          data: { typeId, typeName }
        } = res

        if (!typeName) {
          const { data } = await getQuestionType({ id: typeId })
          res.data.typeName = data && data.name ? data.name : '未知题型'
        }

        res.data.answerScoreable = getAnswerScoreable({
          stem: res.data.question.stem,
          answer: res.data.question.answer
        })
      }
    } catch (error) {
      // console.error(error)
    }

    resovle(res)
  })
}

// 获取打卡情况
export const getTodayStatusApi = (data) => {
  return request.get('/app-api/exam/app/study-clockin/getTodayStatus', data)
}

// 更新打卡情况
export const updateTodayStatusApi = (data) => {
  return request.post('/app-api/exam/app/study-clockin/update', data)
}

// 查询是否存在打卡任务
export const checkStudyClockinApi = (data) => {
  return request.get('/app-api/exam/app/study-clockin/checkStudyClockin', data)
}

// 获取菁优网题目详情
export const getListCompleteByIdsApi = (data) => {
  return request.get('/question-api/question/question/getListCompleteByIds', data)
}

// 更新学生训练表
export const updateStudentTrainApi = (data) => {
  return request.post('/app-api/exam/student-train/update', data)
}
